package com.xiaozhi.iot.websocket;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.druid.util.StringUtils;
import com.xiaozhi.common.entity.AudioParams;
import com.xiaozhi.common.entity.HelloMessageResp;
import com.xiaozhi.common.enums.MessageTypeEnum;
import com.xiaozhi.common.enums.TransportEnum;
import lombok.extern.slf4j.Slf4j;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import org.tio.websocket.common.WsPacket;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.common.WsResponse;
import org.tio.websocket.common.WsSessionContext;
import org.tio.websocket.server.handler.IWsMsgHandler;

/**
 * @Author weirdor
 * @Description
 * @Date 2025/9/5 00:44
 */
@Slf4j
public class XiaoZhiWsMsgHandler implements IWsMsgHandler {

    /**
     * 握手时走这个方法，业务可以在这里获取cookie，request参数等
     */
    @Override
    public HttpResponse handshake(HttpRequest request, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
        String deviceId = request.getHeader("device-id");
        if (StrUtil.isEmpty(deviceId)) {
           log.error("设备ID为空");
           return null;
        }
        Tio.bindUser(channelContext, deviceId);
        log.info("收到来自设备{}的websocket握手包", deviceId);
        return httpResponse;
    }

    /**
     * 握手成功后走这个方法
     */
    @Override
    public void onAfterHandshaked(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
        //更新设备在线状态
    }

    /**
     * 字节消息（binaryType = arraybuffer）过来后会走这个方法
     */
    @Override
    public Object onBytes(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
        log.info("收到字节消息，长度:{}", bytes.length);
        return null;
    }

    /**
     * 当客户端发close flag时，会走这个方法
     */
    @Override
    public Object onClose(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
        Tio.remove(channelContext, "receive close flag");
        return null;
    }

    /*
     * 字符消息（binaryType = blob）过来后会走这个方法
     */
    @Override
    public Object onText(WsRequest wsRequest, String text, ChannelContext channelContext) throws Exception {
        String deviceId = channelContext.userid;
        JSONObject jsonObject = JSONUtil.parseObj(text);
        String id = channelContext.getId();
        AudioParams audioParams = new AudioParams();
        String type = jsonObject.getStr("type");
        log.info("type :{} ", type);
        if(MessageTypeEnum.HELLO.getDesc().equals(type)){
            audioParams = JSONUtil.toBean(jsonObject.getJSONObject("audio_params"), AudioParams.class);
            if(audioParams != null){
                log.info("id :{} 设备：{}音频参数:{}",id, deviceId, audioParams);
            }
        }
        var req = new HelloMessageResp();
        req.setType(MessageTypeEnum.HELLO.getDesc());
        req.setTransport(TransportEnum.WEBSOCKET.getDesc());
        req.setSessionId(id);
        req.setAudioParams(audioParams);
        WsResponse wsResponse = WsResponse.fromText(JSONUtil.toJsonStr(req), WsPacket.CHARSET_NAME);
        Tio.sendToUser(channelContext.tioConfig, deviceId, wsResponse);
        return null;
    }

    public void helloMsg(){

    }



}
